﻿using System.Text;

namespace CodeGenerator {
    /// <summary>
    /// 
    /// </summary>
    public class ControllerCodeFactory {
        #region 全局变量
        static string DalNameSpace = "DiLe.Mes.WebApi.Controllers.Mould";//DAL层命名空间（下同）
        #endregion
        public static string Create(string group,string nsStr,string typeName, string desc) {
            string name = typeName.Replace("Entity", "");
            var clientName = $"{group}{nsStr}";
            StringBuilder sb = new();
            sb.AppendLine($"using DiLe.Mes.Application.Cloud.{group};");
            sb.AppendLine($"using DiLe.Mes.Model.Cloud.{group}.Entity.{nsStr};");
            sb.AppendLine("");
            sb.AppendLine($"namespace {DalNameSpace}.{nsStr} {{");
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// {desc}");
            sb.AppendLine("/// </summary>");
            sb.AppendLine($"[ApiExplorerSettings(GroupName = ApiGroupConst.Organization)]");
            sb.AppendLine($"public class {name}Controller : ApiBaseController {{");
            sb.AppendLine($"private readonly {clientName}Client _{clientName.ToLowerCamelCase()}Client;");
            sb.AppendLine($"private readonly MouldExjosnHandler _handler;");
            sb.AppendLine("/// <summary>");
            sb.AppendLine("/// 构造函数");
            sb.AppendLine("/// </summary>");
            sb.AppendLine($"public {name}Controller({clientName}Client {clientName.ToLowerCamelCase()}, MouldExjosnHandler handler){{");
            sb.AppendLine($"_{clientName.ToLowerCamelCase()}Client = {clientName.ToLowerCamelCase()};");
            sb.AppendLine($" _handler = handler;");
            sb.AppendLine($"}}");


            CrateGetListInfoMethod(clientName, sb, typeName, desc);
            CrateGetInfoMethod(clientName, sb, typeName, desc);
            CrateSaveMethod(clientName, sb, typeName, desc);
            CrateDeleteMethod(clientName, sb, typeName, desc);
            sb.AppendLine("}");
            sb.AppendLine("}");

            var file = CreateTxt($"{name}Controller.cs", sb.ToString());
            return file;
        }
        /// <summary>
        /// 
        /// </summary>
        private static void CrateGetListInfoMethod(string name, StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 获取{desc}列表");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine("[HttpPost]");
            sb.AppendLine($"public async Task<ApiResult> Get{typeName.Replace("Entity", "")}List(QueryParameter parameter){{");
            sb.AppendLine($"var whereExpression = Expressionable.Create<{typeName}>();");
            sb.AppendLine("if (!parameter.Keyword.IsNullOrEmpty()) {");
            sb.AppendLine("whereExpression.Or(p => p.Name.Contains(parameter.Keyword));");
            sb.AppendLine("whereExpression.Or(p => p.Code.Contains(parameter.Keyword));");
            sb.AppendLine("}");
            sb.AppendLine("if (parameter.Pagination == null) {");
            sb.AppendLine($"var res = await _{name.ToLowerCamelCase()}Client.Get{typeName.Replace("Entity", "")}ListAsync(whereExpression.ToExpression());");
            sb.AppendLine("return Success(res);");
            sb.AppendLine("}else {");
            sb.AppendLine($"var res = await _{name.ToLowerCamelCase()}Client.Get{typeName.Replace("Entity", "")}PageListAsync(whereExpression.ToExpression(), parameter.Pagination);");
            sb.AppendLine("return Success(res);");
            sb.AppendLine("}");
            sb.AppendLine("}");
        }
        /// <summary>
        /// 
        /// </summary>
        private static void CrateGetInfoMethod(string name, StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 获取{desc}");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine("[HttpGet]");
            sb.AppendLine($"public async Task<ApiResult> Get{typeName.Replace("Entity", "")}(long id){{");
            sb.AppendLine($" var res = await _{name.ToLowerCamelCase()}Client.Get{typeName.Replace("Entity", "")}InfoAsync(id);");
            sb.AppendLine("return Success(res);");
            sb.AppendLine("}");
        }

        /// <summary>
        /// 
        /// </summary>
        private static void CrateSaveMethod(string name, StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 保存{desc}");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine("[HttpPost]");
            sb.AppendLine($"public async Task<ApiResult> Save{typeName.Replace("Entity", "")}({typeName} entity){{");
            sb.AppendLine($" var resId = await _{name.ToLowerCamelCase()}Client.Save{typeName.Replace("Entity", "")}Async(entity);");
            sb.AppendLine("return resId > 0 ? Success() : Fail();");
            sb.AppendLine("}");
        }

        /// <summary>
        /// 
        /// </summary>
        private static void CrateDeleteMethod(string name, StringBuilder sb, string typeName, string desc) {
            sb.AppendLine("/// <summary>");
            sb.AppendLine($"/// 删除{desc}");
            sb.AppendLine("/// </summary>");
            sb.AppendLine("/// <returns></returns>");
            sb.AppendLine("[HttpPost]");
            sb.AppendLine($"public async Task<ApiResult> Delete{typeName.Replace("Entity", "")}(List<long> ids){{");
            sb.AppendLine($" var res = await _{name.ToLowerCamelCase()}Client.Delete{typeName.Replace("Entity", "")}Async(ids);");
            sb.AppendLine("return res? Success() : Fail();");
            sb.AppendLine("}");
        }


        private static string CreateTxt(string fileName, string str) {
            var filePath = Path.Combine("D:\\新建文件夹", fileName);
            StreamWriter sw = File.CreateText(filePath);
            sw.Write(str);  //写入文件中
            sw.Flush();//清理缓冲区
            sw.Close();//关闭文件
            return filePath;
        }
    }

}
